package com.bs.blogspace.service.impl;

import com.bs.blogspace.mapper.LikeMapper;
import com.bs.blogspace.mapper.SpaceArticleMapper;
import com.bs.blogspace.mapper.UserMapper;
import com.bs.blogspace.model.Result;
import com.bs.blogspace.pojo.Like;
import com.bs.blogspace.pojo.SpaceArticle;
import com.bs.blogspace.pojo.User;
import com.bs.blogspace.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LikeServiceImpl implements LikeService {
    @Autowired
    private LikeMapper likeMapper;
    @Autowired
    private SpaceArticleMapper spaceArticleMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result addLike(Like like) {
        Result result = new Result();
        if (like == null){
          result.setMessage("like 为 null");
          result.setCode("414");
          return result;
        }
        User user = userMapper.findByPhone(like.getLphone());
        if (user == null){
            result.setMessage("该用户不存在");
            result.setCode("414");
            return result;
        }

        SpaceArticle spaceArticle = spaceArticleMapper.showByEssayId(String.valueOf(like.getEssayId()));
        if (spaceArticle == null){
            result.setMessage("该文章不存在");
            result.setCode("414");
            return result;
        }
        if (like.isLike()){
            like.setLavatar(user.getAvatar());
            like.setLuserName(user.getUserName());
            int count = likeMapper.addLike(like);

            if (count == 0){
                result.setMessage("添加点赞失败");
                result.setCode("414");
            }else {
                result.setMessage("点赞成功");
                result.setCode("200");
                result.setSuccess(true);
                result.setData(like);
            }
        }else {
            likeMapper.delete(like);
            result.setCode("200");
            result.setMessage("删除点赞成功");
            result.setSuccess(true);
        }

        return result;
    }
}
